
//创建节点
export function createElement(tag) {
  return document.createElement(tag)
}
//设置文本
export function setElementText(el, text) {
  el.textContent = text
}
//创建文本节点
export function createText(text) {
  el.createTextNode(text)
}
//插入节点
export function insert(el, parent, anchor = null) {
  parent.insertBefore(el, anchor)
}
//挂载属性
export function patchProps(el, key, prevValue, nextValue) {
  if(shouldSetAsProps(el, key)) {//DOM-property
    const {type} = typeof el[key]
    if(type === 'boolean' && nextValue === '') {
      el[key] = false
    }else {
      el[key] = nextValue
    }
  } else if(/^on/.test(key)) {//处理事件
    let invokers = el._vai || (el._vai = {})
    let invoker = invokers[key]
    const name = key.slice(2).toLowerCase()
    if(nextValue) {
      if(!invoker) {
        invoker = el._vai[key] = function(e) {
          if(Array.isArray(invoker.value)) {
            invoker.value.forEach(fn=> fn(e))
          } else {
            invoker.value(e)
          }
        }
        invoker.value = nextValue
        
        el.addEventListener(name, invoker)
      } else {
        invoker.value = nextValue
      } 
    } else if(invoker) {
      el.removeEventListener(name, invoker)
    }
  }else {
    el.setAttribute(key, nextValue)
  }
}
//卸载
export function unmount(vnode) {
  const el = vnode.el
  const parent = el.parentNode
  if(parent) parent.removeChild(el)
}

function shouldSetAsProps(el, key) {
  if(key === 'form' && el.tagName === 'INPUT') return //只读属性
  return key in el
}

const  browserRenderOptions = {
  createElement,
  setElementText,
  createText,
  insert,
  patchProps,
  unmount 
}

export default browserRenderOptions